package com.zdkj.subway.st.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zdkj.common.core.exceltools.ExcelUtil;
import com.zdkj.common.core.exceltools.IExcelExport;
import com.zdkj.common.core.exceltools.IExcelParser;
import com.zdkj.common.core.exceltools.MultipartFileToFile;
import com.zdkj.common.core.util.R;
import com.zdkj.common.core.util.SpringContextHolder;
import com.zdkj.common.log.annotation.SysLog;
import com.zdkj.common.security.service.PigxUser;
import com.zdkj.common.security.util.ObjectUtils;
import com.zdkj.common.security.util.SecurityUtils;
import com.zdkj.subway.st.dto.in.SwOutExportExcelDTO;
import com.zdkj.subway.st.dto.in.SwstOutputDetailDTO;
import com.zdkj.subway.st.dvo.SwStOuputDetailExcelDvo;
import com.zdkj.subway.st.entity.SwStOutputDetail;
import com.zdkj.subway.st.mapper.SwStStockDayCheckDetailMapper;
import com.zdkj.subway.st.service.impl.SwStOutputDetailServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.BeanUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ProjectName: zdkj
 * @Package: com.zdkj.subway.st.controller
 * @ClassName: SwStOutputDetailController
 * @Description:
 * @Author: kangjian
 * @CreateDate: 2020/1/11 9:15
 * @Version: 1.0
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/swStOutputDetail")
@Api(value = "swStOutputDetail", tags = "车票出库管理")
public class SwStOutputDetailController {
    private final SwStOutputDetailServiceImpl swStOutputDetailService;
    @Resource
    private SwStStockDayCheckDetailMapper stStockDayCheckDetailMapper;

    @GetMapping("/{id}")
    public R getById(@PathVariable String id) {
        return R.ok(swStOutputDetailService.getById(id));
    }

    @GetMapping("/page")
    public R<IPage> getDictPage(Page page, SwStOutputDetail swStOutputDetail) {
        List<String> dateCondition = swStOutputDetail.getDates1();
        String stockArea = swStOutputDetail.getStockArea();
        if("0".equals(stockArea)){
            swStOutputDetail.setStockArea(null);
        }
        QueryWrapper queryWrapper = Wrappers.query(swStOutputDetail);
        queryWrapper.orderByDesc("out_going_time");
        if (ObjectUtil.isNotEmpty(dateCondition)) {
            queryWrapper.between("date_format(out_going_time,'%Y-%m-%d')", dateCondition.get(0), dateCondition.get(1));
        }
        if("0".equals(stockArea)){
            queryWrapper.apply("ISNULL(STOCK_AREA)");
        }
        return R.ok(swStOutputDetailService.page(page, queryWrapper));
    }

    @SysLog("车票出库保存信息")
    @PostMapping
    @PreAuthorize("@pms.hasPermission('st_output_detail_add')")
    public R save(@Valid @RequestBody SwstOutputDetailDTO swstOutputDetailDTO) {
        PigxUser user = SecurityUtils.getUser();
        SwStOutputDetail swStOutputDetail = swstOutputDetailDTO.getSwStOutputDetail();
        swStOutputDetail.setKeeper1code(user.getUserCode());
        swStOutputDetail.setKeeper1name(user.getNikeName());
        swStOutputDetail.setDataSource("4");//人工添加
        List<SwStOutputDetail> swStOutputDetails = new ArrayList<>();
        swstOutputDetailDTO.getSwStOutputDetailList().forEach(item -> {
            SwStOutputDetail defaultObj = ObjectUtils.getDefaultObj(SwStOutputDetail.class);
            BeanUtils.copyProperties(swStOutputDetail, defaultObj);
            BeanUtils.copyProperties(item, defaultObj);
            swStOutputDetails.add(defaultObj);
        });
        for(SwStOutputDetail item : swStOutputDetails){
            R r = swStOutputDetailService.saveNew(item);
            int code = r.getCode();
            String msg = r.getMsg();
            if(code == 1){
                return R.failed(msg);
            }
        }
        return R.ok();
    }

    @SysLog("删除车票出库信息")
    @DeleteMapping("/{id}")
    @PreAuthorize("@pms.hasPermission('st_output_detail_delete')")
    public R removeById(@PathVariable String id) {
        return R.ok(swStOutputDetailService.removeById(id));
    }

    /**
     * 通过id批量删除
     * @param idList id
     * @return R
     */
    @ApiOperation(value = "批量删除库区为空的数据", notes = "批量删除库区为空的数据")
    @SysLog("批量删除库区为空的数据")
    @DeleteMapping("/delBatch")
    public R batchRemoveById(@RequestBody List<Integer> idList) {
        //级联删除库存
        Collection<SwStOutputDetail> swStOutputDetails = swStOutputDetailService.listByIds(idList);
        List<Integer> integerList = swStOutputDetails.stream().map(SwStOutputDetail::getStockdayid).collect(Collectors.toList());
        if(CollectionUtil.isNotEmpty(integerList)){
            stStockDayCheckDetailMapper.deleteBatchIds(integerList);
        }
        return R.ok(swStOutputDetailService.removeByIds(idList));
    }

    @PutMapping
    @SysLog("修改车票出库信息")
    @PreAuthorize("@pms.hasPermission('st_output_detail_update')")
    public R updateById(@Valid @RequestBody SwStOutputDetail swStOutputDetail) {
        R r = swStOutputDetailService.updateOutputDetailNew(swStOutputDetail);
        int code = r.getCode();
        String msg = r.getMsg();
        if(code == 1){
            return R.failed(msg);
        }
        return R.ok();
    }

    @PutMapping("/putBatchObj")
    @ApiOperation(value = "车票出库操作和完善信息", notes = "车票出库操作和完善信息")
    public R putBatchObj(@RequestBody SwstOutputDetailDTO swstOutputDetailDTO) {
        List<Integer> ids = swstOutputDetailDTO.getIds();
        SwStOutputDetail outputDetailDto = swstOutputDetailDTO.getSwStOutputDetail();
        boolean a = false;
        //如果ids不为空，就是新增,
        if(CollectionUtil.isNotEmpty(ids)){
            List<SwStOutputDetail> swStOutputDetailList = swStOutputDetailService.getBaseMapper().selectBatchIds(ids);
            for (SwStOutputDetail stOutputDetail : swStOutputDetailList) {
                stOutputDetail.setStockArea(outputDetailDto.getStockArea());
                stOutputDetail.setKeeper2name(outputDetailDto.getKeeper2name());
                stOutputDetail.setKeeper2code(outputDetailDto.getKeeper2code());
                stOutputDetail.setLatestStartTime(outputDetailDto.getLatestStartTime());
                R r = swStOutputDetailService.saveOrUpdateDetail(stOutputDetail);
                int code = r.getCode();
                String msg = r.getMsg();
                if(code == 1){
                    return R.failed(msg);
                }
            }
        }
        //否则就是完善信息操作,先判断修改前库区是否为空，如果为空，就是新增，否则只修改出库数据
        else {
            //获取修改之前的数据,并判断库区
            SwStOutputDetail oldData = swStOutputDetailService.getById(outputDetailDto.getId());
            //是空，新增
            if(StringUtils.isEmpty(oldData.getStockArea())){
                R r = swStOutputDetailService.saveOrUpdateDetail(outputDetailDto);
                int code = r.getCode();
                String msg = r.getMsg();
                if(code == 1){
                    return R.failed(msg);
                }
            }else {
                swStOutputDetailService.updateById(outputDetailDto);
            }
        }
        return R.ok();
    }
    @PutMapping("/applyed")
    @SysLog("出库申请修改")
    @PreAuthorize("@pms.hasPermission('st_output_detail_apply')")
    public R applyed(@Valid @RequestBody List<Integer> ids) {
        return R.ok(swStOutputDetailService.applyedBatch(ids));
    }

    @PutMapping("/approved")
    @SysLog("出库审批修改")
    @PreAuthorize("@pms.hasPermission('st_output_detail_approve')")
    public R approved(@Valid @RequestBody List<Integer> ids) {
        return R.ok(swStOutputDetailService.approvedBatch(ids));
    }

    @PostMapping(value = "/import")
    @SysLog("导入车票出库信息")
    @PreAuthorize("@pms.hasPermission('st_output_detail_import')")
    public R importExcel(@RequestParam("file") MultipartFile file) {
        try {
            File efile= MultipartFileToFile.multipartFileToFile(file);
            Workbook workbook = ExcelUtil.chooseWorkbook(efile);
            Sheet sheet = workbook.getSheetAt(0);
            IExcelParser excelParser = SpringContextHolder.getBean("commonExcelParse");//设置头信息
            List<SwStOutputDetail> list = excelParser.parse(sheet, new SwStOutputDetail());
            swStOutputDetailService.saveBatch(list);
            return R.ok("1","导入成功");
        } catch (Exception e) {
            log.error("",e);
            return R.failed("Excel导入失败！");
        }
    }

    @GetMapping("/export")
    @SysLog("导出车票出库信息")
//    @PreAuthorize("@pms.hasPermission('st_output_detail_export')")
    public void exportExcel(SwStOutputDetail swStOutputDetail, HttpServletResponse response) {
        List<SwStOutputDetail> swStOutputDetaillist=swStOutputDetailService.list(Wrappers.query(swStOutputDetail));
        IExcelExport excelExport= SpringContextHolder.getBean("commonExcelExport");
        Workbook workbook=excelExport.parse(swStOutputDetaillist);
        try {
            workbook.write(response.getOutputStream());
        } catch (IOException e) {
            log.error("",e);
        }
    }
    /**
     * 通过ids导出文件
     * @param response
     */
    @PostMapping("/exportByIds")
    @SysLog("导出车票出库信息")
    public void exportByIds(@RequestBody List<SwStOuputDetailExcelDvo> swStOuputDetailExcelDvo, HttpServletResponse response) {
    	swStOutputDetailService.exportByIds(swStOuputDetailExcelDvo,response);
    }
    /**
     * 导出文件
     * @param response
     */
    @PostMapping("/exportAll")
    @SysLog("导出搜索全部车票出库信息")
    public void exportAll(@RequestBody SwOutExportExcelDTO swOutExportExcelDTO , HttpServletResponse response) {
        swStOutputDetailService.exportAll(swOutExportExcelDTO,response);
    }
}
